import {LogFactory} from "../support/log"
import {filterContainer} from "../containers/filterContainer"

class FilterManager {
  private logger = LogFactory.getLogger("FilterManager")

  static filterList = filterContainer

  static resolveFilter = (Ctor: any) => {
    // 10000以上的是系统保留域
    const order = Math.min(Ctor.__order || 0, 9999)
    const instance = new Ctor()
    instance.__order = order
    FilterManager.filterList.push(instance)
  }

  private static getSortedFilters = () => {
    // @ts-ignore
    return FilterManager.filterList.sort((a, b) => b.__order - a.__order)
  }


  doFilter(req: HttpRequest, resp: HttpResponse, task) {
    const filters = FilterManager.getSortedFilters()
    const length = filters.length
    let index = -1
    const next = (...args: any[]) => {
      index++
      const filter = filters[index]
      if (filter) {
        try {
          filter.doFilter(req, resp, next)
        } catch (e) {
          this.doAfterThrow(req, resp, index, e)
        }
      } else {
        return task(req, resp)
      }
    }
    next()
  }

  doAfterThrow(req: HttpRequest, resp: HttpResponse, index: number, e: Error) {
    const filters = FilterManager.getSortedFilters()
    for (let i = index; i > -1; i--) {
      const filter = filters[i]
      filter.afterThrow(req, resp, e)
    }
  }
}


export {FilterManager}
